##############################################################################
# Generic Makefile for following parts AT90USBx ATMegaxUx
###############################################################################

OUTPUT = .

# General Flags
TARGET = $(PROJECT).elf
CC = avr-gcc
MAKECFG   = config.mk

# Options common to compile, link and assembly rules
COMMON = -mmcu=$(MCU)

# Compile options common for all C compilation units.
CFLAGS = $(COMMON)
CFLAGS += -Wall -Os -fsigned-char 
# -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,-s

# Assembly specific flags
ASMFLAGS = $(COMMON)
ASMFLAGS += -x assembler-with-cpp -Wa,-gdwarf2

# Linker flags
LDFLAGS = $(COMMON)
LDFLAGS += -lc -lm -Wl,-Map=$(PROJECT).map,--cref,--gc-sections,--relax

# Intel Hex file production flags
HEX_FLASH_FLAGS = -R .eeprom

# Eeprom file production flags
HEX_EEPROM_FLAGS = -j .eeprom
HEX_EEPROM_FLAGS += --set-section-flags=.eeprom="alloc,load"
HEX_EEPROM_FLAGS += --change-section-lma .eeprom=0

# Include Directories
INCLUDES = -I.


ADFLAGS=-F -p ATMEGA32U2 -c usbasp
#this is for slow programming
#ADFLAGS=-F -p AT90USB162 -c ftdi -P /dev/ttyUSB0
#fuses - no ext clk - lfuse:w:0xA2:m hfuse:w:0xd9:m

# Include Source files list and part informations
include $(MAKECFG)


## Build
.PHONY: all
all: $(TARGET) $(PROJECT).hex

## Clean target
.PHONY: clean
clean:
	rm -rf $(OBJS) $(PROJECT).elf $(PROJECT).hex $(PROJECT).eep $(PROJECT).map

## Rebuild the project.
.PHONY: rebuild
rebuild: clean all


## Compile

# Create objects files list with sources files
OBJECTS  = $(OBJS)

.PHONY: objfiles clean fuses erase
objfiles: $(OBJECTS)

## Link
$(TARGET): $(OBJECTS)
	$(CC) $(LDFLAGS) $(addprefix $(OUTPUT)/,$(notdir $(OBJECTS))) $(LINKONLYOBJECTS) $(LIBDIRS) $(LIBS) -o $(TARGET)

%.hex: $(TARGET)
	avr-objcopy -O ihex $(HEX_FLASH_FLAGS)  $< $@

%.eep: $(TARGET)
	avr-objcopy $(HEX_EEPROM_FLAGS) -O ihex $< $@  || exit 0

%.lss: $(TARGET)
	avr-objdump -h -S $< > $@

eep: ${TARGET}.eep
	avrdude $(ADFLAGS) -V -U eeprom:w:$(TARGET).eep:i

prog: ${TARGET}.hex
	avrdude $(ADFLAGS) -V -U flash:w:$(TARGET).hex:i

fuses:
	avrdude $(ADFLAGS) -U lfuse:w:0xe2:m -U hfuse:w:0xd1:m #http://www.engbedded.com/cgi-bin/fc.cgi 

erase:
	avrdude $(ADFLAGS) -E noreset -e
